package com.ijustyce.denoise.Activity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.icu.text.SimpleDateFormat;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.ijustyce.denoise.Adapter.MyFileAdapter;
import com.ijustyce.denoise.Menu;
import com.ijustyce.denoise.R;
import com.ijustyce.denoise.SettleDoc.MyFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

@RequiresApi(api = Build.VERSION_CODES.N)
public class OptimizeActivity extends AppCompatActivity {

    private static final String LOG_TAG = "AudioRecordTest";
    private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
    private static String fileName = null;

    Calendar now=new GregorianCalendar();
    SimpleDateFormat simpleDate = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
//    String fileName=simpleDate.format(now.getTime());

    private MediaRecorder recorder = null;

    private MediaPlayer player = null;

    boolean mStartRecording = true;

    // Requesting permission to RECORD_AUDIO
    private boolean permissionToRecordAccepted = false;
    private String [] permissions = {Manifest.permission.RECORD_AUDIO};

    private List<MyFile> myFileList = new ArrayList<>();
    private MyFileAdapter adapter;

    private SwipeRefreshLayout swip_1;

    private Timer timer=null;
    private TimerTask timerTask=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_optimize);

        fileName = getExternalCacheDir().getAbsolutePath();
        System.out.println(fileName);

        System.out.println(fileName);

        Start();

        initRecyclerView();

    }

//    Handler handler = new Handler() {
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//
//        }
//    };


    private void Start(){
        swip_1 = this.findViewById(R.id.swip);
//        System.out.println(swip_1);
        swip_1.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initRecyclerView();
                swip_1.setRefreshing(false);
            }
        });
    }

    private void onRecord(boolean start) {
        if (start) {
            startRecording();
        } else {
            stopRecording();
        }
    }

    private void onPlay(boolean start) {
        if (start) {
            startPlaying();
        } else {
            stopPlaying();
        }
    }

    private void startPlaying() {
        player = new MediaPlayer();
        try {
            player.setDataSource(fileName);
            player.prepare();
            player.start();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }
    }

    private void stopPlaying() {
        player.release();
        player = null;
    }

    private void startRecording() {
        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
//        recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
        recorder.setOutputFile(fileName);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            recorder.prepare();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }

        try {
            recorder.start();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }

    }

    private void stopRecording() {
        recorder.stop();
        recorder.release();
        recorder = null;
    }

    private void initRecyclerView() {
        adapter = new MyFileAdapter(myFileList);
        initMyFile(getExternalCacheDir());
        RecyclerView recyclerView = findViewById(R.id.detail_recyclerView);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
        //设置layoutManager,可以设置显示效果，是线性布局、grid布局，还是瀑布流布局
        //参数是：上下文、列表方向（横向还是纵向）、是否倒叙
        recyclerView.setLayoutManager(new LinearLayoutManager(OptimizeActivity.this, LinearLayoutManager.VERTICAL, false));
        //设置item的分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(OptimizeActivity.this,DividerItemDecoration.VERTICAL));
        //RecyclerView中没有item的监听事件，需要自己在适配器中写一个监听事件的接口。参数根据自定义OnItemClickListener()
        adapter.setOnItemClickListener(new MyFileAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(MyFile data) {
                //此处进行监听事件的业务处理
                System.out.println(data.getFileName());
                //创建Intent对象

            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void initMyFile(File sourceFile) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            myFileList.clear();
        }
        List<File> files = new ArrayList<>();
        Collections.addAll(files, sourceFile.listFiles());
        for (File file : files) {
            String fileName = file.getName();
            //默认是未知文件
            int imageId = R.mipmap.ic_launcher_round;

            //下面开始判断
            if (file.isDirectory()) {
                imageId = R.mipmap.ic_launcher_round;
            } else {
                //如果是文件，就从文件名的后缀名来判断是什么文件，从而添加对应图标
                //获取后缀名前的分隔符"."在fName中的位置。
                int dotIndex = fileName.lastIndexOf(".");
                if(dotIndex >= 0){
                    /* 获取文件的后缀名*/
                    String end= fileName.substring(dotIndex,fileName.length()).toLowerCase();
                    if(!Objects.equals(end, "")){
                        if (Objects.equals(end, ".mp3")||Objects.equals(end, ".ape")
                                ||Objects.equals(end, ".flac")||Objects.equals(end, ".m4a")
                                ||Objects.equals(end, ".ape")||Objects.equals(end, ".wav")
                                ||Objects.equals(end, ".aac")){
                            //如果是音乐文件
                            imageId = R.mipmap.music;
                        }
//                        else if (Objects.equals(end, ".mp4")||Objects.equals(end, ".mkv")
//                                ||Objects.equals(end, ".avi")||Objects.equals(end, ".rmvb")
//                                ||Objects.equals(end, ".rm")||Objects.equals(end, ".mov")
//                                ||Objects.equals(end, ".mpeg")){
//                            //如果是影视文件
//                            imageId = R.mipmap.ic_launcher_round;
//                        }
                    }
                }
            }

            String fileSize = "";
            long size = 0;
            //下面开始判断文件大小
            if (file.isDirectory()) {
                //如果是文件夹就要求出占用大小 = 总大小 - 可用大小
                try {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        size = getTotalSizeOfFilesInDir(file);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                size = file.length();
            }
            //判断大小是该用什么单位,K\M\G
            if (size / 1024 / 1024 / 1024 > 0) {
                fileSize = size / 1024 / 1024 / 1024 + " G";
            } else if (size / 1024 / 1024 > 0) {
                fileSize = size / 1024 / 1024 + " M";
            } else {
                fileSize = size / 1024 + " K";
            }

            String filePower = "";
            StringBuilder builder = new StringBuilder();
            builder.append("-");
            if (file.canRead()) builder.append("r");
            if (file.canWrite()) builder.append("w");
            if (file.canExecute()) builder.append("x");
            filePower = builder.toString();

            String fileDate = "";
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                fileDate = getModifiedTime_2(file);
            }

            MyFile myFile = new MyFile(fileName, imageId, fileSize, filePower, fileDate);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                myFileList.add(myFile);
            }
        }
//        adapter.notifyDataSetChanged();
    }

    public static String getModifiedTime_2(File f){
        Calendar cal = Calendar.getInstance();
        long time = f.lastModified();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        cal.setTimeInMillis(time);
        return formatter.format(cal.getTime());
    }

    private class SubDirectoriesAndSize {

        final public long size;
        final public List<File> subDirectories;

        public SubDirectoriesAndSize(final long totalSize,
                                     final List<File> theSubDirs) {
            size = totalSize;
            subDirectories = Collections.unmodifiableList(theSubDirs);
        }
    }

    private OptimizeActivity.SubDirectoriesAndSize getTotalAndSubDirs(final File file) {
        long total = 0;
        final List<File> subDirectories = new ArrayList<File>();
        if (file.isDirectory()) {
            final File[] children = file.listFiles();
            if (children != null)
                for (final File child : children) {
                    if (child.isFile())
                        total += child.length();
                    else
                        subDirectories.add(child);
                }
        }
        return new OptimizeActivity.SubDirectoriesAndSize(total, subDirectories);
    }

    private long getTotalSizeOfFilesInDir(final File file)
            throws InterruptedException, ExecutionException, TimeoutException {
        final ExecutorService service = Executors.newFixedThreadPool(100);
        try {
            long total = 0;
            final List<File> directories = new ArrayList<File>();
            directories.add(file);
            while (!directories.isEmpty()) {
                final List<Future<OptimizeActivity.SubDirectoriesAndSize>> partialResults = new ArrayList<Future<OptimizeActivity.SubDirectoriesAndSize>>();
                for (final File directory : directories) {
                    partialResults.add(service
                            .submit(new Callable<OptimizeActivity.SubDirectoriesAndSize>() {
                                public OptimizeActivity.SubDirectoriesAndSize call() {
                                    return getTotalAndSubDirs(directory);
                                }
                            }));
                }
                directories.clear();
                for (final Future<OptimizeActivity.SubDirectoriesAndSize> partialResultFuture : partialResults) {
                    final OptimizeActivity.SubDirectoriesAndSize subDirectoriesAndSize = partialResultFuture
                            .get(100, TimeUnit.SECONDS);
                    directories.addAll(subDirectoriesAndSize.subDirectories);
                    total += subDirectoriesAndSize.size;
                }
            }
            return total;
        } finally {
            service.shutdown();
        }
    }
    public void onBackPressed() {
        Intent intent1 = new Intent(this, Menu.class);
        startActivity(intent1);
        finish();
    }

}